<?php
namespace App\Service\Admin;

use App\Http\Controllers\Admin\PrizeController;
use App\Models\Prize;
use App\Repositories\Eloquent\PrizeRepositoryEloquent;
use App\Service\Admin\BaseService;
use DB;
use Exception;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 门票service
 */
class PrizeService extends BaseService
{

    private $prize;

    function __construct(PrizeRepositoryEloquent $prize)
    {
        $this->prize = $prize;
    }

    /**
     * datatables获取数据
     * @author 晚黎
     * @date   2016-11-02T10:31:46+0800
     * @return [type]                   [description]
     */
    public function ajaxList()
    {
        $name = request('name');
        // datatables请求次数
        $draw = request('draw', 1);
        // 开始条数
        $start = request('start', config('admin.golbal.list.start'));
        // 每页显示数目
        $length = request('length', config('admin.golbal.list.length'));
        // datatables是否启用模糊搜索
        $search['regex'] = request('search.regex', false);
        // 搜索框中的值
        $search['value'] = request('search.value', '');
        // 排序
        $order['name'] = request('columns.' . request('order.0.column', 0) . '.name');
        $order['dir'] = request('order.0.dir', 'asc');

        $result = $this->prize->getPrizeList($start, $length, $search, $order, $name);

        $prizes = [];

        if ($result['prizes']) {
            foreach ($result['prizes'] as $v) {
                $v->actionButton = '';
                $prizes[] = $v;
            }
        }

        return [
            'draw' => $draw,
            'recordsTotal' => $result['count'],
            'recordsFiltered' => $result['count'],
            'data' => $prizes,
        ];
    }

    /**
     * 添加门票
     * @author 晚黎
     * @date   2016-11-02T10:32:18+0800
     * @param  [type]                   $formData [表单中所有的数据]
     * @return [type]                             [true or false]
     */
    public function storePrize($formData)
    {
        try {
            $result = $this->prize->create($formData);
            flash_info($result, trans('act/alert.prize.create_success', ['action' => '活动']),
                trans('act/alert.prize.create_error'));
            return $result;
        } catch (Exception $e) {
            // 错误信息发送邮件
            $this->sendSystemErrorMail(env('MAIL_SYSTEMERROR', ''), $e);
            return false;
        }
    }

    /**
     * 批量导入
     * @param Request $request
     * @param $id
     * @return bool
     */
    public function batchStorePrize(Request $request)
    {
        $name = $request->input('name');
        $deadline = $request->input('deadline');
        $url = $request->input('url');
        $value = intval($request->input('value'));
        if (empty($name)) {
            return false;
        }
        //无cdkey
        $noNumber = $request->input('noNumber');
        if ($noNumber) {
            $noNumber = intval($noNumber);
            for ($i = 0; $i < $noNumber; $i++) {
                $this->prize->create([
                    'name' => $name,
                    'value' => $value,
                    'deadline' => $deadline,
                    'url' => $url
                ]);
            }
        }

        //有座位号
        $file = $request->file('file');
        if ($file) {
            Excel::load($file->getRealPath(), function ($reader) use ($name, $value, $deadline, $url) {
                $result = $reader->toArray();
                foreach ($result as $row) {
                    foreach ($row as $item) {
                        if (!empty($item)) {
                            $this->prize->create([
                                'number' => $item,
                                'name' => $name,
                                'value' => $value,
                                'deadline' => $deadline,
                                'url' => $url
                            ]);
                        }
                    }
                }
            });
        }
        return true;
    }

    /**
     * 根据ID获取门票数据
     * @author 晚黎
     * @date   2016-11-02T11:44:36+0800
     * @param  [type]                   $id [门票id]
     * @return [type]                       [查询出来的门票对象，查不到数据时跳转404]
     */
    public function editView($id)
    {
        $prize = $this->prize->find($id);
        if ($prize) {
            return $prize;
        }
        abort(404);
    }

    /**
     * 修改门票
     * @author 晚黎
     * @date   2016-11-02T12:45:00+0800
     * @param  [type]                   $attributes [表单数据]
     * @param  [type]                   $id         [resource路由传递过来的id]
     * @return [type]                               [true or false]
     */
    public function updatePrize($attributes, $id)
    {
        // 防止用户恶意修改表单id，如果id不一致直接跳转500
        if ($attributes['id'] != $id) {
            abort(500);
        }
        try {
            $result = $this->prize->update($attributes, $id);
            flash_info($result, trans('admin/alert.prize.edit_success'), trans('admin/alert.prize.edit_error'));
            return $result;
        } catch (Exception $e) {
            // 错误信息发送邮件
            $this->sendSystemErrorMail(env('MAIL_SYSTEMERROR', ''), $e);
            return false;
        }
    }

    /**
     * 门票暂不做状态管理，直接删除
     * @author 晚黎
     * @date   2016-11-02T13:23:45+0800
     * @param  [type]                   $id [门票id]
     * @return [type]                       [true or false]
     */
    public function destroyPrize($id)
    {
        try {
            $result = $this->prize->delete($id);
            flash_info($result, trans('admin/alert.prize.destroy_success'), trans('admin/alert.prize.destroy_error'));
            return $result;
        } catch (Exception $e) {
            // 错误信息发送邮件
            $this->sendSystemErrorMail(env('MAIL_SYSTEMERROR', ''), $e);
            return false;
        }

    }

    /**
     * 获取门票统计数据
     * @param $id
     * @return array
     */
    public function getPrizesStat()
    {
        // datatables请求次数
        $draw = request('draw', 1);

        $total = Prize::select(DB::raw('name, COUNT(*) as total'))->groupBy('name')->get();
        $init = Prize::select(DB::raw('name, COUNT(*) as init'))->where('openid', null)->groupBy('name')->get();

        $statusArr = json_decode(\Cache::get(Prize::cacheStatusKey, '[]'), true);
        $result = [];
        foreach ($total as $item) {
            $buttonHtml = '<a href="' . url('admin/prize/all?name=' . $item->name) . '" class="btn btn-xs btn-outline btn-primary tooltips" data-original-title="奖品列表"  data-placement="top"><i class="fa fa-gift"></i></a> '
                . '<button class="btn btn-xs btn-outline btn-warning tooltips" data-name="' . $item->name . '" data-original-title="切换状态"  data-placement="top" onclick="changeStatus(this)"><i class="fa fa-cog"></i></button> ';
            $left = $init->first(function ($value, $key) use ($item) {
                return $value->name == $item->name;
            });
            $result[] = [
                'name' => $item->name,
                'total' => $item->total,
                'left' => empty($left) ? 0 : $left->init,
                'status' => empty($statusArr[$item->name]) ? '<span class="status-span">未启用</span>' : '<span class="status-span" style="color: blue">已启用</span>',
                'actionButton' => $buttonHtml,
            ];
        }

        return [
            'draw' => $draw,
            'recordsTotal' => count($result),
            'recordsFiltered' => count($result),
            'data' => $result,
        ];
    }
}